import { _decorator, Component, Node } from 'cc';
const { ccclass, property } = _decorator;

declare const TonConnectSDK: any;
declare const TonConnectUI: any;

@ccclass('TonConnectManager')
export class TonConnectManager extends Component {
    @property(Node)
    tonConnectContainer: Node = null!;

    start() {
        this.initializeTonConnect();
    }

    private initializeTonConnect() {
        // 动态引入 TonConnect-UI 脚本
        const script = document.createElement('script');
        script.src = 'path/to/tonconnect-ui.js';  // 替换为实际路径
        document.head.appendChild(script);

        script.onload = () => {
            // 初始化 TonConnect SDK 和 TonConnect-UI
            const tonConnect = new TonConnectSDK();

            const tonConnectUI = new TonConnectUI({
                tonConnect,
                // 可选配置项
                callbackUrl: 'https://your-callback-url.com',
            });

            // 创建并添加 TonConnect-UI 按钮到 Cocos Creator 的节点中
            const tonConnectButton = tonConnectUI.renderButton();
            this.tonConnectContainer.addChild(tonConnectButton);

            // 处理连接事件
            tonConnect.on('connected', (wallet: any) => {
                console.log('Wallet connected:', wallet);
                // 处理连接成功后的逻辑
            });

            tonConnect.on('disconnected', () => {
                console.log('Wallet disconnected');
                // 处理断开连接后的逻辑
            });
        };
    }
}
